var dgram = require("dgram");
var fs = require('fs');
var http = require('http');
var util = require('util');
var exec = require('child_process').exec;

var DeviceManager = function(server, callback) {
	this.server = server;
	this.callback = callback;
	deviceManager = this;

	fs.readFile('./Configuration/deviceManager.json', function(e, content) {
		if (e)
			throw e;

		deviceManager.config = JSON.parse(content);
		
		if (typeof (deviceManager.callback) == 'function') {
			deviceManager.callback();
		}
	});
	
	
};

DeviceManager.prototype.locate = function() {
	var client = dgram.createSocket("udp4");
	client.setBroadcast(true);
	
	var msg = new Buffer("Discovery: Who is out there?");

	client.on('listening', function() {
		client.send(msg, 0, msg.length, deviceManager.config.locateBdcstPort, '255.255.255.255', function(e) {
			if (e)
				util.log(e.message + "\n" + e.stack);

			deviceManager.server.Models.Device.remove({ status : 'noconf' }, function(e) {
				if (e)
					util.log(e.message + "\n" + e.stack);
			});

			deviceManager.server.Models.Device.update({ status : 'online' }, { status : 'offline' }, function(e) {
				if (e)
					util.log(e.message + "\n" + e.stack);
			});
		});

	});

	client.on("message", function(message, rinfo) {
		var messageFields = message.toString().match(/(.*?)\s+\r\n([0-9a-fA-f\-]{17})/);
		deviceManager.server.Models.Device.findOne({ hwAddress : messageFields[2] }, function(e, device) {
			if (device) {
				device.status = 'online';
				device.inetAddress = rinfo.address;
				device.save(function(e) {
					if (e)
						util.log(e.message + "\n" + e.stack);
				});
			} else {
				var device = new deviceManager.server.Models.Device();
				device.status = 'noconf';
				device.hwAddress = messageFields[2];
				device.inetAddress = rinfo.address;
				device.name = messageFields[1];
				device.save(function(e) {
					if (e)
						util.log(e.message + "\n" + e.stack);
				});
			}
		});
	});
	
	
	client.bind(deviceManager.config.locateBindPort, deviceManager.config.locateBindAddress);
};

module.exports = DeviceManager;

// HTTPClient.prototype.get = function(host) {
// var options = {
// host : host,
// port : 80,
// agent : this.agent
// };
//
// var req = http.request(options, function(res) {
// res.setEncoding('utf8');
// res.on('data', function(chunk) {
// // console.log('BODY: ' + chunk);
// });
// });
//
// util.log(util.inspect(req));
//
// util.log(util.inspect(this.agent));
//
// req.on('error', function(e) {
// console.log('problem with request: ' + e.message);
// });
//
// // write data to request body
// req.write('data\n');
// req.write('data\n');
// req.end();
// };
